<template>
  <div ref="el">
    <slot></slot>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { useVModel } from '@vueuse/core'
/**
 * 外部参数
 */
let props = defineProps({
  number: { type: Number, default: () => 0 },
  target: { type: String, required: true },
  disabled: { type: Boolean, default: () => false },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:number'])
/**
 * 双向绑定
 */
let number = useVModel(props, 'number', emit)
/**
 * 监听增加执行动画
 */
watch(number, (newNumber, oldNumber) => {
  if (newNumber > oldNumber && !props.disabled) {
    createBall()
  }
})
let el = ref()
function createBall() {
  let startElement = el.value
  let startRect = startElement.getBoundingClientRect()
  let bar = document.createElement('div')
  bar.style.position = 'fixed'
  bar.style.top = startRect.top + startRect.height / 2 + 'px'
  bar.style.left = startRect.left + startRect.width / 2 + 'px'
  bar.style.width = '5px'
  bar.style.height = '5px'
  bar.style.borderRadius = '50%'
  bar.style.backgroundColor = 'red'
  bar.style.transition =
    'left .3s linear, top .6s cubic-bezier(0.5, -0.5, 1, 1)'
  document.body.appendChild(bar)
  setTimeout(() => {
    let endElement = document.querySelector(props.target)
    let endRect = endElement.getBoundingClientRect()
    bar.style.top = endRect.top + endRect.height / 2 + 'px'
    bar.style.left = endRect.left + endRect.width / 2 + 'px'
  })
  // bar.ontransitionend = function () {
  //   document.body.removeChild(bar)
  // }
  setTimeout(() => {
    document.body.removeChild(bar)
  }, 300)
}
defineExpose({
  play() {
    createBall()
  },
})
</script>
